package router

import (
	_ "fmt"
	"math/rand"
	"net/http"

	"gitee.com/wang_cyi/govue/api"
	"github.com/gin-gonic/gin"
)

// Init Init
func Init() {
	r := gin.Default()
	//内置功能
	r.GET("/ping", func(c *gin.Context) {
		c.JSON(200, gin.H{
			"message": "pong",
		})
	})
	v1 := r.Group("/v1")
	{
		//http://localhost:8000/v1/line
		v1.GET("/line", func(c *gin.Context) {
			// 注意:在前后端分离过程中，需要注意跨域问题，因此需要设置请求头
			c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
			legendData := []string{"周一", "周二", "周三", "周四", "周五", "周六", "周日"}
			xAxisData := []int{120, 240, rand.Intn(500), rand.Intn(500), 150, 230, 180}
			c.JSON(200, gin.H{
				"legend_data": legendData,
				"xAxis_data":  xAxisData,
			})
		})
		//api 2
		v1 := r.Group("/v1")
		{
			v1.GET("/hello", api.HelloPage)
		}

	}
	//HTML 渲染 加载模板
	r.LoadHTMLGlob("templates/*")
	v2 := r.Group("/v2")
	{
		v2.GET("/index", func(c *gin.Context) {
			c.HTML(http.StatusOK, "index.html", gin.H{"title": "hello Gin."})
		})
	}

	//定义默认路由
	r.NoRoute(func(c *gin.Context) {
		c.JSON(http.StatusNotFound, gin.H{
			"status": 404,
			"error":  "404, page not exists!",
		})
	})

	r.Run(":8080")
}
